package easypsync.app;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class PIMSyncService extends Service {

	private static final String TAG=PIMSyncService.class.getName();
	
	private final Timer timer = new Timer();
	
	/**
	 * triggered when wifi is connected with certain SSID.
	 */
	private final BroadcastReceiver wifiReceiver = new BroadcastReceiver(){
		 @Override public void onReceive(Context context, Intent intent) {
			  
		  int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE , WifiManager.WIFI_STATE_UNKNOWN);
		 
		  switch(extraWifiState){
		  case WifiManager.WIFI_STATE_ENABLED:
			  WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
			  
			  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PIMSyncService.this.getBaseContext());
			  
			  // read SSID to cover
			  final String ssid = prefs.getString("target_ssid", "");
			  
			  for(WifiConfiguration wi : wifi.getConfiguredNetworks()) {
				  if (wi.SSID != null && ssid.equals(wi.SSID.replaceAll("\"", ""))) {
					  long timeSinceLastSuccess = System.currentTimeMillis() - prefs.getLong("last_success", 0);
					  if (timeSinceLastSuccess > getInterval()) {
						  doSync();
					  }
				  }
			  }
			  break;
		  }
	}};
	
	/**
	 * timer task which is executed repeatedly.
	 */
	private final TimerTask task = new TimerTask() {
		@Override public void run() {
			doSync();
		}
	};
	
	SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		  public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
			  if (key.equals("interval")) {
				  long timeSinceLastSuccess = System.currentTimeMillis() - prefs.getLong("last_success", 0);
				  if (timeSinceLastSuccess > getInterval()) {
					  doSync();
				  }
			  }
		  }
	};

	
	private final synchronized void doSync() {
		Log.i(TAG, "Now starting action...");
		try {
			PIMSync ps = new PIMSync(PIMSyncService.this.getBaseContext());
	    	ps.doSync();
		} catch (Throwable e) {
			Log.e(TAG, e.getMessage(), e);
		}
		
    	Log.i(TAG, "Now starting action...done");
	}

	@Override public void onDestroy() {
		Log.i(TAG, "onDestroy");
		timer.cancel();
		unregisterReceiver(wifiReceiver);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PIMSyncService.this.getBaseContext());
		prefs.unregisterOnSharedPreferenceChangeListener(prefListener);
		super.onDestroy();
	}

	@Override public void onCreate() {
		Log.i(TAG, "onCreate");
		super.onCreate();
	}
	
	@Override public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "onStartCommand");
		
		// 
		// Register WIFI receiver
		//
		registerReceiver( wifiReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));

		
		//
		// Register TimerTask for continous execution.
		//
		timer.scheduleAtFixedRate(task , getTimeToNext(), getInterval());
		
		//
		// Register for preference changes, for resetting the interval
		//
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PIMSyncService.this.getBaseContext());
		prefs.registerOnSharedPreferenceChangeListener(prefListener);
		
		return START_STICKY;
	}

	private long getTimeToNext() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PIMSyncService.this.getBaseContext());
		long timeSinceLastSuccess = System.currentTimeMillis() - prefs.getLong("last_success", 0);
		  if (timeSinceLastSuccess > getInterval()) {
			  return 0;
		  } else {
			  return getInterval() - timeSinceLastSuccess;
		  }
	}

	private long getInterval() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(PIMSyncService.this.getBaseContext());
		int interval = Integer.valueOf( prefs.getString("interval", "3600000"));
		return interval;
	}

	@Override public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);		
	}

	@Override public IBinder onBind(Intent arg0) {
		return null;
	}
}
